/*
 * @Author: 大司马
 * @Date: 2021-01-12 09:44:17
 * @LastEditors: 大司马
 * @LastEditTime: 2021-01-12 09:46:14
 * @FilePath: \open-platform-ui\platform-pc-console\src\libs\transformImgs.js
 */

/**
 * 网络图像文件转Base64
 */
export const getBase64Image = (img) => {
  var canvas = document.createElement('canvas')
  canvas.width = img.width
  canvas.height = img.height
  var ctx = canvas.getContext('2d')
  ctx.drawImage(img, 0, 0, img.width, img.height)
  var ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase()
  var dataURL = canvas.toDataURL('image/' + ext)
  return dataURL
}

/**
 *Base64字符串转二进制
 */
export const dataURLtoBlob = (dataurl) => {
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new Blob([u8arr], {
    type: mime
  })
}

/** blob to dataURL
 * 二进制转base64
 */
export const blobToDataURL = (blob, callback) => {
  var a = new FileReader()
  a.onload = function (e) {
    callback(e.target.result)
  }
  a.readAsDataURL(blob)
  return a
}
